package com.wsc.wsckeeper.components;

import android.content.Context;
import android.text.InputFilter;
import android.util.AttributeSet;
import android.view.View;
import android.widget.EditText;

public class CardNumberEditText extends EditText {
	private static final int GROUP_NUMBER = 4;
	private static final int MAX_LENGTH = 16;

	private boolean isFormatted = true;
	private OnFocusChangeListener listener = new OnFocusChangeListener() {

		@Override
		public void onFocusChange(View v, boolean hasFocus) {

			if (hasFocus) {
				if (isEnabled())
					setFilters(new InputFilter[] { new InputFilter.LengthFilter(MAX_LENGTH) });
				else
					setFilters(new InputFilter[] { new InputFilter.LengthFilter(MAX_LENGTH + 3) });

				isFormatted = false;
				setText(getText().toString().replaceAll(" ", ""));
				isFormatted = true;
			} else {
				setFilters(new InputFilter[] { new InputFilter.LengthFilter(MAX_LENGTH + 3) });
				setText(getText());
			}
		}
	};

	public CardNumberEditText(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	public CardNumberEditText(Context context, AttributeSet attrs) {
		super(context, attrs);
		setOnFocusChangeListener(listener);
	}

	public CardNumberEditText(Context context) {
		super(context);
	}

	@Override
	public void setText(CharSequence text, BufferType type) {
		if (!isEnabled() || isFormatted) {
			StringBuilder value = new StringBuilder(text);
			for (int i = GROUP_NUMBER; i < value.length(); i = i + GROUP_NUMBER) {
				value.insert(i, " ");
				i++;
			}
			text = value;
		}
		super.setText(text, type);
	}
}
